package com.mftour.common.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mftour.common.Constant;
import com.mftour.common.cache.InitCache;
import com.mftour.common.utils.JsonUtil;
import com.mftour.moudles.entity.User;
import com.mftour.moudles.vo.AjaxResponse;

public class AuthorizationInterceptor implements HandlerInterceptor {

	// private final Logger logger =
	// Logger.getLogger(AuthorizationInterceptor.class);

	private String[] notInterceptUrls;

	public void setNotInterceptUrls(String[] notInterceptUrls) {
		this.notInterceptUrls = notInterceptUrls;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView modelandview) throws Exception {
		// modelandview.setViewName("login");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

		
		String referer = request.getHeader("Referer");
		if (referer != null && !referer.trim().equals("")) {
			if (referer.endsWith("swagger-ui.html")) {
				response.setHeader("test", "test abc");
				return true;
				// authorization="BearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJMYWJQb28xIiwiYXVkIjoiRTAxMDAwMEsiLCJleHAiOjE0ODE3ODkxOTIsImlhdCI6MTQ4MTc4NzM5Mn0.eXYOOrwnptA9YTsikXqxCwubwLwCrfpr7xNB38MUmcs";
			}
		}
		
		String context = request.getContextPath();
		String requestUrl = request.getRequestURI().replace(context, "");
		
		//加入对跨域的支持
//		response.setHeader("Access-Control-Allow-Credentials", "*");
//		response.setHeader("Access-Control-Allow-Origin", "*");
//		response.setHeader("Access-Control-Allow-Headers", "content-type,authorization");
		
		// 设置不拦截路径
		if (requestUrl.indexOf("appController") != -1) {
			return true;
		}
		
		for (String notInterceptUrl : notInterceptUrls) {
			if (requestUrl.equals(notInterceptUrl)) {
				return true;
			}
		}

		HttpSession session = request.getSession(false);

		if (session == null || session.getAttribute(Constant.SESSION_LOGIN_USER) == null) {
			String head = request.getHeader("x-requested-with");
			if (head != null && head.equalsIgnoreCase("XMLHttpRequest")) {// 异步请求

				AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_ERROR, "连接超时");
				response.getWriter().write(JsonUtil.writeValueAsString(ajaxResponse));
			} else { // 同步请求
				response.sendRedirect(context + "/login/loginIndex");
			}
			return false;
		} else {
			if (requestUrl.indexOf("/ajax/") != -1) {// 异步请求
				// ajax请求
				if (requestUrl.equals("/user/ajax/entity")) {
					User loginUser = (User) session.getAttribute(Constant.SESSION_LOGIN_USER);
					Map<String, Integer> menuMap = InitCache.allUserMenuMap.get(loginUser.getUserId());
					if (menuMap.get("/user/list") == null) {
						response.sendError(HttpServletResponse.SC_FORBIDDEN);
						return false;
					}
				}
			} else if (!requestUrl.equals("/login/main")) {
				User loginUser = (User) session.getAttribute(Constant.SESSION_LOGIN_USER);
				Map<String, Integer> menuMap = InitCache.allUserMenuMap.get(loginUser.getUserId());
				if (menuMap.get(requestUrl) == null) {
					response.sendError(HttpServletResponse.SC_FORBIDDEN);
					return false;
				}
			}
		}
		return true;
	}

}
